use iced::{Element, Length, Color};
use iced::widget::{container, column, row, text, button, scrollable, text_input, Space};
use crate::theme::CdbTheme;
use chrono::{DateTime, Utc};
use std::collections::VecDeque;

/// 查询历史记录项
#[derive(Debug, Clone)]
pub struct QueryHistoryItem {
    pub id: String,
    pub query: String,
    pub executed_at: DateTime<Utc>,
    pub execution_time: Option<u64>, // 执行时间（毫秒）
    pub status: QueryStatus,
    pub result_count: Option<usize>,
    pub database: String,
    pub is_favorite: bool,
}

/// 查询执行状态
#[derive(Debug, Clone, PartialEq)]
pub enum QueryStatus {
    Success,
    Error(String),
    Running,
    Cancelled,
}

impl QueryStatus {
    pub fn icon(&self) -> &'static str {
        match self {
            QueryStatus::Success => "✅",
            QueryStatus::Error(_) => "❌",
            QueryStatus::Running => "⏳",
            QueryStatus::Cancelled => "⏹️",
        }
    }

    pub fn color(&self) -> Color {
        match self {
            QueryStatus::Success => Color::from_rgb(0.2, 0.8, 0.2),
            QueryStatus::Error(_) => Color::from_rgb(0.8, 0.2, 0.2),
            QueryStatus::Running => Color::from_rgb(0.8, 0.8, 0.2),
            QueryStatus::Cancelled => Color::from_rgb(0.6, 0.6, 0.6),
        }
    }
}

impl QueryHistoryItem {
    pub fn new(query: String, database: String) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            query,
            executed_at: Utc::now(),
            execution_time: None,
            status: QueryStatus::Running,
            result_count: None,
            database,
            is_favorite: false,
        }
    }

    /// 格式化执行时间
    pub fn formatted_execution_time(&self) -> String {
        match self.execution_time {
            Some(time) if time < 1000 => format!("{}ms", time),
            Some(time) => format!("{:.1}s", time as f64 / 1000.0),
            None => "N/A".to_string(),
        }
    }

    /// 格式化查询预览（截取前50个字符）
    pub fn query_preview(&self) -> String {
        let preview = self.query.trim().replace('\n', " ");
        if preview.len() > 50 {
            format!("{}...", &preview[..47])
        } else {
            preview
        }
    }

    /// 格式化执行时间
    pub fn formatted_time(&self) -> String {
        self.executed_at.format("%H:%M:%S").to_string()
    }

    /// 格式化日期
    pub fn formatted_date(&self) -> String {
        self.executed_at.format("%Y-%m-%d").to_string()
    }
}

/// 查询历史管理器
#[derive(Debug, Clone)]
pub struct QueryHistory {
    items: VecDeque<QueryHistoryItem>,
    max_items: usize,
    search_query: String,
    show_favorites_only: bool,
    filter_status: Option<QueryStatus>,
}

#[derive(Debug, Clone)]
pub enum QueryHistoryMessage {
    SearchChanged(String),
    ToggleFavoritesOnly,
    SetStatusFilter(Option<QueryStatus>),
    ToggleFavorite(String),
    RerunQuery(String),
    DeleteQuery(String),
    ClearHistory,
    ExportHistory,
    ClearSearch,
}

impl QueryHistory {
    pub fn new() -> Self {
        Self {
            items: VecDeque::new(),
            max_items: 1000,
            search_query: String::new(),
            show_favorites_only: false,
            filter_status: None,
        }
    }

    /// 添加查询到历史记录
    pub fn add_query(&mut self, query: String, database: String) -> String {
        let item = QueryHistoryItem::new(query, database);
        let id = item.id.clone();
        
        self.items.push_front(item);
        
        // 保持最大数量限制
        if self.items.len() > self.max_items {
            self.items.pop_back();
        }
        
        id
    }

    /// 更新查询状态
    pub fn update_query_status(&mut self, id: &str, status: QueryStatus, execution_time: Option<u64>, result_count: Option<usize>) {
        if let Some(item) = self.items.iter_mut().find(|item| item.id == id) {
            item.status = status;
            item.execution_time = execution_time;
            item.result_count = result_count;
        }
    }

    /// 切换收藏状态
    pub fn toggle_favorite(&mut self, id: &str) {
        if let Some(item) = self.items.iter_mut().find(|item| item.id == id) {
            item.is_favorite = !item.is_favorite;
        }
    }

    /// 删除查询
    pub fn delete_query(&mut self, id: &str) {
        self.items.retain(|item| item.id != id);
    }

    /// 清空历史记录
    pub fn clear_history(&mut self) {
        self.items.clear();
    }

    /// 获取过滤后的查询列表
    fn get_filtered_items(&self) -> Vec<&QueryHistoryItem> {
        self.items
            .iter()
            .filter(|item| {
                // 搜索过滤
                if !self.search_query.is_empty() {
                    let query_lower = self.search_query.to_lowercase();
                    if !item.query.to_lowercase().contains(&query_lower)
                        && !item.database.to_lowercase().contains(&query_lower) {
                        return false;
                    }
                }

                // 收藏夹过滤
                if self.show_favorites_only && !item.is_favorite {
                    return false;
                }

                // 状态过滤
                if let Some(ref filter_status) = self.filter_status {
                    if std::mem::discriminant(&item.status) != std::mem::discriminant(filter_status) {
                        return false;
                    }
                }

                true
            })
            .collect()
    }

    /// 渲染搜索和过滤控件
    fn render_controls<'a>(&'a self, theme: &CdbTheme) -> Element<'a, QueryHistoryMessage> {
        let search_input = text_input("搜索查询历史...", &self.search_query)
            .on_input(QueryHistoryMessage::SearchChanged)
            .size(12)
            .padding(8);

        let clear_button = button(text("✕").size(12))
            .on_press(QueryHistoryMessage::ClearSearch)
            .style(|theme: &iced::Theme, status| {
                button::Style {
                    background: Some(Color::TRANSPARENT.into()),
                    text_color: Color::from_rgb(0.6, 0.6, 0.6),
                    border: iced::Border::default(),
                    shadow: iced::Shadow::default(),
                }
            });

        let search_row = row![
            search_input,
            clear_button
        ]
        .spacing(5)
        .align_y(iced::Alignment::Center);

        // 过滤按钮
        let filter_buttons = row![
            self.create_status_filter_button("全部", None, theme),
            self.create_status_filter_button("成功", Some(QueryStatus::Success), theme),
            self.create_status_filter_button("错误", Some(QueryStatus::Error("".to_string())), theme),
        ]
        .spacing(5);

        // 操作按钮
        let action_buttons = row![
            self.create_toggle_button("收藏夹", self.show_favorites_only, QueryHistoryMessage::ToggleFavoritesOnly, theme),
            button(text("清空历史").size(10))
                .on_press(QueryHistoryMessage::ClearHistory)
                .style(|theme: &iced::Theme, status| {
                    button::Style {
                        background: Some(Color::from_rgb(0.8, 0.2, 0.2).into()),
                        text_color: Color::WHITE,
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                })
                .padding([4, 8]),
            button(text("导出").size(10))
                .on_press(QueryHistoryMessage::ExportHistory)
                .style(|theme: &iced::Theme, status| {
                    button::Style {
                        background: Some(Color::from_rgb(0.2, 0.6, 0.2).into()),
                        text_color: Color::WHITE,
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                })
                .padding([4, 8]),
        ]
        .spacing(5);

        column![
            search_row,
            filter_buttons,
            action_buttons,
        ]
        .spacing(8)
        .padding(10)
        .into()
    }

    /// 创建状态过滤按钮
    fn create_status_filter_button<'a>(
        &self,
        label: &'a str,
        status: Option<QueryStatus>,
        _theme: &CdbTheme,
    ) -> Element<'a, QueryHistoryMessage> {
        let is_active = match (&self.filter_status, &status) {
            (None, None) => true,
            (Some(current), Some(filter)) => {
                std::mem::discriminant(current) == std::mem::discriminant(filter)
            }
            _ => false,
        };

        button(text(label).size(10))
            .on_press(QueryHistoryMessage::SetStatusFilter(status))
            .style(move |_theme: &iced::Theme, _status| {
                if is_active {
                    button::Style {
                        background: Some(Color::from_rgb(0.2, 0.4, 0.8).into()),
                        text_color: Color::WHITE,
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                } else {
                    button::Style {
                        background: Some(Color::from_rgb(0.1, 0.1, 0.1).into()),
                        text_color: Color::from_rgb(0.8, 0.8, 0.8),
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                }
            })
            .padding([4, 8])
            .into()
    }

    /// 创建切换按钮
    fn create_toggle_button<'a>(
        &self,
        label: &'a str,
        is_active: bool,
        message: QueryHistoryMessage,
        _theme: &CdbTheme,
    ) -> Element<'a, QueryHistoryMessage> {
        button(text(label).size(10))
            .on_press(message)
            .style(move |_theme: &iced::Theme, _status| {
                if is_active {
                    button::Style {
                        background: Some(Color::from_rgb(0.2, 0.6, 0.2).into()),
                        text_color: Color::WHITE,
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                } else {
                    button::Style {
                        background: Some(Color::from_rgb(0.1, 0.1, 0.1).into()),
                        text_color: Color::from_rgb(0.8, 0.8, 0.8),
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                }
            })
            .padding([4, 8])
            .into()
    }

    /// 渲染历史记录列表
    fn render_history_list<'a>(&'a self, theme: &CdbTheme) -> Element<'a, QueryHistoryMessage> {
        let filtered_items = self.get_filtered_items();
        
        if filtered_items.is_empty() {
            return container(
                text("没有查询历史记录")
                    .size(14)
                    .color(theme.colors.muted_foreground)
            )
            .center_x(Length::Fill)
            .center_y(Length::Fill)
            .width(Length::Fill)
            .height(Length::Fill)
            .into();
        }

        let mut list = column![];

        for item in filtered_items {
            list = list.push(self.render_history_item(item, theme));
        }

        scrollable(list)
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
    }

    /// 渲染单个历史记录项
    fn render_history_item<'a>(&'a self, item: &'a QueryHistoryItem, theme: &CdbTheme) -> Element<'a, QueryHistoryMessage> {
        let status_icon = text(item.status.icon())
            .size(14)
            .color(item.status.color());

        let favorite_icon = if item.is_favorite { "⭐" } else { "☆" };
        let favorite_button = button(text(favorite_icon).size(12))
            .on_press(QueryHistoryMessage::ToggleFavorite(item.id.clone()))
            .style(|theme: &iced::Theme, status| {
                button::Style {
                    background: Some(Color::TRANSPARENT.into()),
                    text_color: Color::from_rgb(1.0, 0.8, 0.0),
                    border: iced::Border::default(),
                    shadow: iced::Shadow::default(),
                }
            });

        let header = row![
            status_icon,
            text(&item.database).size(10).color(theme.colors.muted_foreground),
            Space::new(Length::Fill, Length::Fixed(0.0)),
            text(item.formatted_time()).size(10).color(theme.colors.muted_foreground),
            favorite_button,
        ]
        .spacing(5)
        .align_y(iced::Alignment::Center);

        let query_text = text(item.query_preview())
            .size(12)
            .color(theme.colors.foreground);

        let footer = row![
            text(item.formatted_execution_time()).size(10).color(theme.colors.muted_foreground),
            Space::new(Length::Fill, Length::Fixed(0.0)),
            button(text("重新运行").size(10))
                .on_press(QueryHistoryMessage::RerunQuery(item.id.clone()))
                .style(|theme: &iced::Theme, status| {
                    button::Style {
                        background: Some(Color::from_rgb(0.2, 0.4, 0.8).into()),
                        text_color: Color::WHITE,
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                })
                .padding([2, 6]),
            button(text("删除").size(10))
                .on_press(QueryHistoryMessage::DeleteQuery(item.id.clone()))
                .style(|theme: &iced::Theme, status| {
                    button::Style {
                        background: Some(Color::from_rgb(0.8, 0.2, 0.2).into()),
                        text_color: Color::WHITE,
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                })
                .padding([2, 6]),
        ]
        .spacing(5)
        .align_y(iced::Alignment::Center);

        let item_content = column![
            header,
            query_text,
            footer,
        ]
        .spacing(5)
        .padding(10);

        container(item_content)
            .style(|theme: &iced::Theme| {
                container::Style {
                    background: Some(Color::from_rgb(0.05, 0.05, 0.05).into()),
                    border: iced::Border {
                        color: Color::from_rgb(0.2, 0.2, 0.2),
                        width: 1.0,
                        radius: 4.0.into(),
                    },
                    ..Default::default()
                }
            })
            .width(Length::Fill)
            .into()
    }

    /// 渲染完整的查询历史面板
    pub fn view<'a>(&'a self, theme: &CdbTheme) -> Element<'a, QueryHistoryMessage> {
        column![
            self.render_controls(theme),
            self.render_history_list(theme),
        ]
        .spacing(5)
        .into()
    }
}

impl Default for QueryHistory {
    fn default() -> Self {
        Self::new()
    }
}
